import uuid
import json
from bottle import Bottle, run, request, static_file
import os
import utils.config as config

fileUploadServiceApp = Bottle()

# 设置上传目录
UPLOAD_DIR = config.UPLOAD_DIR

# 创建上传目录（如果不存在）
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)


@fileUploadServiceApp.route('/', method=['POST'])
def do_upload():
    print(request.files)
    upload = request.files.get('file')  # 获取上传文件
    result = {
        "code": 500,
        "message": "新增反馈信息",
        "data": ""
    }
    if upload:
        fileName = f"{uuid.uuid1()}.{upload.filename.split('.')[-1]}"
        if upload:
            # 检查文件类型
            if upload.content_type.startswith('image/'):
                # 保存文件
                upload.save(os.path.join(UPLOAD_DIR, fileName))
                result["data"] = f"/file_upload/get_file?filename={fileName}"
                result["code"] = 200

    return json.dumps(result, ensure_ascii=False)


@fileUploadServiceApp.route('/get_file', method=['GET'])
def get_file():
    filename = request.query.filename
    return static_file(filename, root=UPLOAD_DIR)
